const App = getApp();
const {
  $resHost
} = App.globalData;
const _ = require('../../pages/Common/underscore.js'),
  $extConfig = xhs.getExtConfigSync(),
  $config = require('../../config.js'),
  $appId = $extConfig.appId || $config.appId;
Component({
  properties: {
    isNew: {
      type: Boolean,
      value: false,
      observer(isNew) {
        this.data.listURL = isNew ? '/user/ec-goods/get-list' : '/user/goods/get-list';
      }
    }
  },
  data: {
    classId: '',
    nameList: [],
    classes: [],
    attr: [],
    attributs: [],
    search: '',
    serviceId: '',
    className: '',
    toggle: false,
    filterToggle: false,
    isFix: false,
    //右侧列表是否显示
    useEntityGoodsClass: '0',
    //0为类目，1为店铺分类
    orderByToggle: false,
    orderByType: 0,
    orderByName: '默认排序',
    orderByNameList: ['默认排序', '价格最高', '价格最低', '最新上架'],
    list: [],
    count: 0,
    pageSize: 10,
    icon1: `${$resHost}/img/site/1.png`,
    icon2: `${$resHost}/img/site/2.png`,
    icon3: 'https://res.gde3f.com/upload/images/20241230/22ab3165d3f84c2fabe185d90b4f2152.png',
    defaultPng: `${$resHost}/img/site/12.jpg`,
    shareEmployeeId: '',
    shareUserId: '',
    listURL: '/user/goods/get-list'
  },
  lifetimes: {
    ready() {
      const pages = getCurrentPages().pop();
      const {
        orgId = '',
        classId = '',
        shareEmployeeId = '',
        shareUserId = '',
        type = '',
        searchName = '',
        useEntityGoodsClass = ''
      } = pages.options;
      this.setData({
        orderByType: this.data.isNew ? 3 : 5,
        orderByNameList: this.data.isNew ? ['价格最高', '价格最低', '默认排序'] : ['价格最高', '价格最低', '最新上架', '默认排序'],
        orgId,
        classId,
        shareEmployeeId,
        shareUserId,
        type,
        search: searchName,
        searchName,
        useEntityGoodsClass: useEntityGoodsClass || '0' //0为类目，1为店铺分类
      }, () => {
        this.getAttrs();
        this.getCategories();
      });
      pages.onReachBottom = this.onReachBottom.bind(this);
    }
  },
  methods: {
    // 右侧列表显示按钮
    pageBtn() {
      this.setData({
        isFix: true
      });
    },
    //右侧列表空白点击
    fixHide() {
      this.setData({
        isFix: false
      });
    },
    //右侧列表防冒泡，必须有，虽然没内容
    fixStopBu() {},
    //右侧列表关闭按钮
    fixClose() {
      this.setData({
        isFix: false
      });
    },
    setOrderByToggle() {
      xhs.showActionSheet({
        itemList: this.data.isNew ? ['价格最高', '价格最低', '默认排序'] : ['价格最高', '价格最低', '最新上架', '默认排序'],
        //'默认排序'=用户标签排序
        success: res => {
          this.setData({
            currentPage: 1,
            list: [],
            orderByType: res.tapIndex > 2 ? res.tapIndex + 2 : res.tapIndex + 1,
            orderByName: this.data.orderByNameList[res.tapIndex]
          }, () => {
            this.getList();
          });
        }
      });
    },
    onReachBottom() {
      const {
        list: {
          length
        },
        count,
        pageSize
      } = this.data;
      if (count > length) {
        this.getList(Math.floor(length / pageSize + 1));
      }
    },
    onSearch(e) {
      debugger;
      this.setData({
        currentPage: 1,
        list: [],
        search: e.detail.value
      }, () => {
        this.getList();
      });
    },
    setToggle() {
      this.setData({
        toggle: !this.data.toggle
      });
    },
    setFilterToggle() {
      this.setData({
        isFix: !this.data.isFix
      });
    },
    getClassName(data) {
      var result = [],
        that = this;
      for (var i = 0; i < data.length; i++) {
        if (Array.isArray(data[i].child) && data[i].child.length > 0) {
          var tempResult = that.getClassName(data[i].child);
          for (var j = 0; j < tempResult.length; j++) {
            result.push(tempResult[j]);
          }
        }
        result.push(data[i]);
      }
      return result;
    },
    getCategories() {
      let config = xhs.getStorageSync('config');
      if (config == '') {
        this.getConfigFn();
      } else {
        this.getCategoriesFn();
      }
    },
    getConfigFn() {
      App.$getData('/site/config', {
        appId: $appId
      }).then(data => {
        this.getCategoriesFn();
      });
    },
    getCategoriesFn() {
      var url = '/user/goodsclass/getlist';
      var param = {
        isAll: true
      };
      let that = this;
      if (this.data.useEntityGoodsClass == '1') {
        url = '/user/goodsclassentity/getlist';
        param = {
          orgId: this.data.orgId,
          type: 1
        };
      }
      App.$getData(url, param).then(data => {
        var list = data.data.map(function (e) {
          return e.id;
        });
        that.data.classes = [{
          id: '',
          className: '全部'
        }].concat(data.data || []);
        if (!~list.indexOf(this.data.classId)) {
          this.data.nameList = that.getClassName(data.data);
        }
        this.setData({
          classes: _.map(that.data.classes, function (re) {
            if (!re.className) {
              re.className = re.name;
            }
            re.isShow = false;
            _.map(re.child, function (res) {
              if (!res.className) {
                res.className = res.name;
              }
              res.isShow = false;
              _.map(res.child, function (ress) {
                if (!ress.className) {
                  ress.className = ress.name;
                }
                ress.isShow = false;
              });
            });
            return re;
          })
        });
        this.getList();
        this.className2Fn();
      });
    },
    className2Fn() {
      var classId = this.data.classId;
      var list = this.data.classes.concat(this.data.nameList);
      this.setData({
        className2: (list.filter(function (c) {
          return c.id === classId;
        })[0] || {}).className || '全部'
      });
    },
    getList(currentPage = 1) {
      const {
        list,
        pageSize,
        type,
        listURL
      } = this.data;
      let vm = this.data;
      console.log(this.data);
      const param = {
          orgId: vm.orgId,
          orderType: vm.orderByType,
          currentPage,
          pageSize
        },
        classId = vm.classId,
        search = {};
      if (vm.search) {
        search.goodsName = vm.search;
      }
      if (classId) {
        if (vm.useEntityGoodsClass == '0') {
          _.extend(search, {
            classId: classId
          });
        } else {
          param.entityGoodsClassId = classId;
        }
      }
      if (!_.isEmpty(vm.attr)) {
        search.attr = vm.attr;
      }
      if (type === '1') {
        search.classTypeSelected = 1;
      }
      if (!_.isEmpty(search)) {
        param.search = search;
      }
      App.$getData(listURL, param).then(data => {
        if (data.errCode == '0') {
          this.setData({
            list: currentPage === 1 ? data.data : [...list, ...data.data],
            count: +data.count
          });
        } else {
          this.setData({
            list: []
          });
          xhs.showToast({
            title: data.errInfo,
            icon: 'none'
          });
        }
      });
    },
    getAttrs() {
      var vm = this;
      App.$getData('/user/goods-attr/get-list', {
        classId: this.data.classId || 0
      }).then(function (data) {
        vm.data.attributs = (data.data || []).filter(function (dt) {
          return dt !== '1';
        }).map(function (dt) {
          dt.select = [];
          return dt;
        });
        vm.setData({
          attributs: vm.data.attributs
        });
        vm.reset();
      });
    },
    select(attr, value) {
      var index = attr.select.indexOf(value);
      if (~index) {
        attr.select.splice(index, 1);
      } else {
        attr.select.push(value);
      }
    },
    reset() {
      var _attrs = this.data.attr;
      this.data.attributs.forEach(function (attr) {
        attr.select = (_.findWhere(_attrs, {
          attrId: attr.id
        }) || {}).attrValue || [];
      });
      this.setData({
        attributs: this.data.attributs,
        isFix: false
      });
    },
    resetAll() {
      this.data.attributs.forEach(function (attr) {
        attr.select = [];
        attr.attrVal = _.each(attr.attrVal, function (res) {
          res.on = false;
          return res;
        });
      });
      this.setData({
        attributs: this.data.attributs
      });
    },
    submit() {
      var query = this.data.attributs.filter(function (attr) {
        return attr.select.length;
      }).map(function (attr) {
        return {
          attrId: attr.id,
          attrValue: attr.select
        };
      });
      this.setData({
        attr: query,
        isFix: false
      }, () => {
        this.getList();
      });
    },
    showView(e) {
      let {
        v,
        k
      } = e.currentTarget.dataset;
      let boolFn = !(v.child && v.child.length > 0);
      if (boolFn) {
        this.setClassId(v);
        return;
      }
      this.data.classes[k].isShow = !v.isShow;
      this.setData({
        classes: this.data.classes
      });
    },
    showChildView(e) {
      let {
        vv,
        k,
        kk
      } = e.currentTarget.dataset;
      let boolFn = !(vv.child && vv.child.length > 0);
      if (boolFn) {
        this.setClassId(vv);
        return;
      }
      this.data.classes[k].child[kk].isShow = !vv.isShow;
      this.setData({
        classes: this.data.classes
      });
    },
    setClassId(e) {
      let {
        v
      } = e.currentTarget.dataset;
      this.setData({
        classId: v.id,
        className: v.className,
        toggle: false
      }, () => {
        this.getList();
        this.getAttrs();
      });
    },
    selectFn(e) {
      let {
        index,
        vid,
        kk
      } = e.currentTarget.dataset;
      let obj = this.data.attributs[index];
      if (!obj.attrVal[kk].on) {
        obj.attrVal[kk].on = true;
      } else {
        obj.attrVal[kk].on = !obj.attrVal[kk].on;
      }
      var indexs = obj.select.indexOf(vid);
      if (~indexs) {
        obj.select.splice(indexs, 1);
      } else {
        obj.select.push(vid);
      }
      this.setData({
        attributs: this.data.attributs
      });
    }
  }
});